/*
 * ========================================================
 * Copyright(c) 2014 杭州偶尔科技-版权所有
 * ========================================================
 * 本软件由杭州偶尔科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 *
 * 			http://www.kkkd.com/
 *
 * ========================================================
 */
package com.simon.mengkou.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ouertech.android.agm.lib.base.future.core.AgnettyFuture;
import com.ouertech.android.agm.lib.base.future.core.AgnettyResult;
import com.ouertech.android.agm.lib.base.utils.UtilString;
import com.ouertech.android.agm.lib.ui.base.BaseDialog;
import com.ouertech.android.agm.lib.ui.base.defaults.activity.BaseTopActivity;
import com.simon.mengkou.R;
import com.simon.mengkou.alipay.Alipay;
import com.simon.mengkou.alipay.PayResult;
import com.simon.mengkou.data.bean.base.Address;
import com.simon.mengkou.data.bean.base.Image;
import com.simon.mengkou.data.bean.base.NewOrder;
import com.simon.mengkou.data.bean.base.Order;
import com.simon.mengkou.data.bean.base.Product;
import com.simon.mengkou.data.bean.base.Store;
import com.simon.mengkou.data.enums.EOrderStatus;
import com.simon.mengkou.data.enums.EPayResult;
import com.simon.mengkou.future.base.OuerFutureListener;
import com.simon.mengkou.system.constant.CstOuer;
import com.simon.mengkou.system.global.OuerApplication;
import com.simon.mengkou.system.global.OuerDispatcher;
import com.simon.mengkou.ui.adapter.OrderNewDetailAdapter;
import com.simon.mengkou.ui.adapter.OrderProductAdapter;
import com.simon.mengkou.ui.dialog.CommonConfirmDialog;
import com.simon.mengkou.ui.dialog.PayDialog;
import com.simon.mengkou.utils.UtilOuer;
import com.simon.mengkou.wxpay.Wxpay;
import com.tencent.mm.sdk.modelbase.BaseResp;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * @author : Zhenshui.Xia
 * @since : 2016/3/24.
 * desc    : 订单详情界面
 */
public class OrderNewDetailActivity extends BaseTopActivity
        implements Alipay.AlipayListener{
    @Bind(R.id.order_detail_id_list)
    ListView mLvList;
    //
    @Bind(R.id.order_detail_id_delete)
    TextView mBtnDelete;
    //
    @Bind(R.id.order_detail_id_info)
    TextView mBtnInfo;
    //底部
    @Bind(R.id.order_detail_id_root)
    RelativeLayout mRlBottom;

    //订单状态
    TextView mTvStatus;
    //订单编号
    TextView mTvNo;
    //地址
    TextView mTvAddress;
    //姓名
    TextView mTvName;

    //商品总价
    TextView mTvAmount;
    //优惠
    TextView mTvDiscount;
    //运费
    TextView mTvFreight;
    //总价
    TextView mTvTotal;


    private OrderNewDetailAdapter mAdapter;
    private String mOrderId;
    private NewOrder mOrder;


    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        Intent intent = getIntent();
        mOrderId = intent.getStringExtra(CstOuer.KEY.ID);
    }

    @Override
    protected void initTop() {
        setTitle(R.string.my_order_detail_title);
        setNavigation(R.drawable.common_ic_left_nav);
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_order_detail);
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);

        //头部
        View header = LayoutInflater.from(this).inflate(R.layout.layout_order_detail_header, null);
        mTvStatus = (TextView)header.findViewById(R.id.order_detail_id_status);
        mTvNo = (TextView)header.findViewById(R.id.order_detail_id_no);
        mTvAddress = (TextView)header.findViewById(R.id.order_detail_id_address);
        mTvName = (TextView)header.findViewById(R.id.order_detail_id_name);
        mLvList.addHeaderView(header);

        //尾部
        View footer = LayoutInflater.from(this).inflate(R.layout.layout_order_detail_footer, null);
        mTvAmount = (TextView)footer.findViewById(R.id.order_detail_id_total_amount);
        mTvFreight = (TextView)footer.findViewById(R.id.order_detail_id_freight);
        mTvTotal = (TextView)footer.findViewById(R.id.order_detail_id_total);
        mTvDiscount = (TextView)footer.findViewById(R.id.order_detail_id_discount);
        mLvList.addFooterView(footer);

        mAdapter = new OrderNewDetailAdapter(this);
        mLvList.setAdapter(mAdapter);


        //失败重试
        setOnRetryListener(new OnRetryListener() {
            @Override
            public void onRetry() {
                getOrderDetail();
            }
        });

        //获取数据
        getOrderDetail();

        //注册微信支付结果广播
        registerAction(CstOuer.BROADCAST_ACTION.WEIXIN_PAY_ACTION);
    }

    @Override
    protected void onReceive(Intent intent) {
        super.onReceive(intent);
        //微信支付结果
        if(CstOuer.BROADCAST_ACTION.WEIXIN_PAY_ACTION.equals(intent.getAction())) {
            int code = intent.getIntExtra(CstOuer.KEY.CODE, BaseResp.ErrCode.ERR_SENT_FAILED);
            if(code == BaseResp.ErrCode.ERR_OK) {//支付成功
                OuerDispatcher.presentPayResultActivity(this, mOrder, null, EPayResult.SUCCESS);
                OuerDispatcher.sendOrderPayBroadcast(this);
                finish();
            } else if(code == BaseResp.ErrCode.ERR_SENT_FAILED) {//微信支付失败
                OuerDispatcher.presentPayResultActivity(this, mOrder, null, EPayResult.FAILURE);
                finish();
            }
        }
    }


    /**
     * 获取订单详情
     */
    private void getOrderDetail() {
        AgnettyFuture future = OuerApplication.mOuerFuture.orderDetail(
                mOrderId,
                new OuerFutureListener(this){

                    public void onStart(AgnettyResult result) {
                        setLoading(true);
                    }

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        setLoading(false);
                        mOrder = (NewOrder) result.getAttach();
                        setOrder(mOrder);
                    }

                    public void onNetUnavaiable(AgnettyResult result) {
                        super.onNetUnavaiable(result);
                        setRetry(true);
                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);
                        setRetry(true);
                    }
                });

        attachDestroyFutures(future);
    }

    /**
     * 后台获取订单详情
     */
    private void getOrderDetailBackground() {
        AgnettyFuture future = OuerApplication.mOuerFuture.orderDetail(
                mOrderId,
                new OuerFutureListener(this){

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        setLoading(false);
                        mOrder = (NewOrder) result.getAttach();
                        setOrder(mOrder);
                    }

                    public void onNetUnavaiable(AgnettyResult result) {
                        //super.onNetUnavaiable(result);
                    }

                });

        attachDestroyFutures(future);
    }


    private void setOrder(final NewOrder data) {
        if(data == null) {
            return;
        }

        //订单状态
        switch (data.getStatus()) {
            case EOrderStatus.UNPAID://待付款
                mTvStatus.setText(getString(R.string.my_order_detail_status,
                        getString(R.string.my_order_status_unpaid)));
                mBtnDelete.setText(R.string.my_order_detail_compute);
                mBtnInfo.setVisibility(View.VISIBLE);
                mBtnInfo.setText(R.string.my_order_detail_delete);
                mRlBottom.setVisibility(View.VISIBLE);
                break;
            case EOrderStatus.SENDING://配送中
                mTvStatus.setText(getString(R.string.my_order_detail_status,
                        getString(R.string.my_order_status_sending)));
                mBtnDelete.setText(R.string.my_order_detail_confirm);
                mBtnInfo.setVisibility(View.GONE);
                mRlBottom.setVisibility(View.VISIBLE);
                break;
            case EOrderStatus.FINISH://已完成
                mTvStatus.setText(getString(R.string.my_order_detail_status,
                        getString(R.string.my_order_status_finish)));
                mBtnInfo.setVisibility(View.GONE);
                mRlBottom.setVisibility(View.GONE);
                break;
            case EOrderStatus.GROUPPENDING://团进行中
                mTvStatus.setText(getString(R.string.my_order_detail_status,
                        getString(R.string.my_order_status_grouppending)));
                mBtnDelete.setText(R.string.group_group_buy_cancel);
                mBtnInfo.setVisibility(View.GONE);
                mRlBottom.setVisibility(View.VISIBLE);
                break;
            case EOrderStatus.CANCEL://已取消
                mTvStatus.setText(getString(R.string.my_order_detail_status,
                        getString(R.string.my_order_status_cancel)));
                mBtnInfo.setVisibility(View.GONE);
                mRlBottom.setVisibility(View.GONE);
                break;
            default:
                break;
        }


        mBtnInfo.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                if(EOrderStatus.UNPAID == data.getStatus()) {
                    new CommonConfirmDialog(OrderNewDetailActivity.this,
                            R.string.my_order_detail_delete_tips,
                            new BaseDialog.OnLeftListener() {
                                @Override
                                public void onLeft() {
                                    cancelOrder();
                                }
                            }).show();

                }


            }
        });

        mBtnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int status = data.getStatus();
                if(EOrderStatus.SENDING == status) {
                    confirmOrder();
                } else if(EOrderStatus.UNPAID == status) {
                    PayDialog dialog = new PayDialog(OrderNewDetailActivity.this, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int id = v.getId();
                            if (id == R.id.pay_id_alipay) {//支付宝支付
                                new Alipay(OrderNewDetailActivity.this).pay(data, OrderNewDetailActivity.this);
                            } else if (id == R.id.pay_id_wxpay) {//微信支付
                                new Wxpay(OrderNewDetailActivity.this).pay(data);
                            }
                        }
                    });

                    dialog.showAtLocation(mTvStatus, Gravity.CENTER, 0, 0);

                }
            }
        });

        //订单编号
        mTvNo.setText(getString(R.string.my_order_detail_no, data.getId()));
        Address addr = data.getAddress();
        if(addr != null) {
            //地址
            mTvAddress.setText(getString(R.string.my_order_detail_address,
                    UtilString.nullToEmpty(addr.getAddress()) + UtilString.nullToEmpty(addr.getDetail())));
            //姓名
            mTvName.setText(getString(R.string.my_order_detail_name,
                    UtilString.nullToEmpty(addr.getName()),
                    UtilString.nullToEmpty(addr.getPhone())));
        }

        //商品总价
        mTvAmount.setText(getString(R.string.common_price,
                UtilOuer.formatPrice(data.getTotalAmount())));
        //运费
        mTvFreight.setText(getString(R.string.common_price,
                UtilOuer.formatPrice(data.getFreight())));

        //优惠
        mTvDiscount.setText(getString(R.string.common_price,
                UtilOuer.formatPrice(data.getDiscount())));
        //实付总价
        mTvTotal.setText(Html.fromHtml(getString(R.string.my_order_detail_total,
                UtilOuer.formatPrice(data.getAmount()))));

        //商品列表
        mAdapter.setTime(data.getCreateAt());
        mAdapter.setList(data.getStoreList());
    }

    /**
     * 取消订单
     */
    private void cancelOrder() {
        AgnettyFuture future = OuerApplication.mOuerFuture.cancelOrder(mOrderId,
                new OuerFutureListener(this){
                    @Override
                    public void onStart(AgnettyResult result) {
                        super.onStart(result);
                        setWaitingDialog(true);
                    }

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        setWaitingDialog(false);
                        Boolean flag = (Boolean)result.getAttach();
                        if(flag) {
                            UtilOuer.toast(OrderNewDetailActivity.this, R.string.my_order_detail_delete_success);
                            getOrderDetailBackground();
                        } else {
                            UtilOuer.toast(OrderNewDetailActivity.this, R.string.my_order_detail_delete_failure);
                        }
                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);
                        setWaitingDialog(false);
                        UtilOuer.toast(OrderNewDetailActivity.this, R.string.my_order_detail_delete_failure);
                    }

                    @Override
                    public void onNetUnavaiable(AgnettyResult result) {
                        super.onNetUnavaiable(result);
                        setWaitingDialog(false);
                    }
                });

        attachDestroyFutures(future);
    }



    /**
     * 确认收货
     */
    private void confirmOrder() {
        AgnettyFuture future = OuerApplication.mOuerFuture.confirmOrder(mOrderId,
                new OuerFutureListener(this){
                    @Override
                    public void onStart(AgnettyResult result) {
                        super.onStart(result);
                        setWaitingDialog(true);
                    }

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        setWaitingDialog(false);
                        UtilOuer.toast(OrderNewDetailActivity.this, R.string.my_order_detail_confirm_success);
                        getOrderDetailBackground();
                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);
                        setWaitingDialog(false);
                        UtilOuer.toast(OrderNewDetailActivity.this, R.string.my_order_detail_confirm_failure);
                    }

                    @Override
                    public void onNetUnavaiable(AgnettyResult result) {
                        super.onNetUnavaiable(result);
                        setWaitingDialog(false);
                    }
                });

        attachDestroyFutures(future);
    }


    @Override
    public void onResult(PayResult payResult) {
        String resultStatus = payResult.getResultStatus();

        // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
        if (TextUtils.equals(resultStatus, "9000")) {
            OuerDispatcher.presentPayResultActivity(this, mOrder, null, EPayResult.SUCCESS);
            OuerDispatcher.sendOrderPayBroadcast(this);
            finish();
        } else {
            OuerDispatcher.presentPayResultActivity(this, mOrder, null, EPayResult.FAILURE);
            finish();
        }
    }
}
